<?php

class OaUserRoles extends \Formax\Model
{

    /**
     *
     * @var integer
     */
    public $user_id;

    /**
     *
     * @var integer
     */
    public $role_id;

    // 获取所有记录
    public static function getAll()
    {
        static $cached = null;

        if ($cached === null) {
            $cached = array();
            foreach (self::find() as $row) {
                $cached[] = $row->toArray();
            }
        }

        return $cached;
    }

    // 根据角色ID，查找用户
    public static function findUsersByRoles($roles, $fields = null, $orderBy = null)
    {
        if (! is_array($roles)) {
            $roles = array($roles);
        }

        $roles = array_filter($roles, function ($id) {
            return $id && is_numeric($id);
        });

        if (empty($roles)) return false;

        $rows = array_filter(self::getAll(), function ($row) use ($roles) {
            return in_array($row['role_id'], $roles);
        });
        if (! count($rows)) return false;

        $users = OaUsers::find(array(
            'user_id in (' . implode(',', array_pick($rows, 'user_id')) . ')',
            'columns' => $fields,
            'order'   => $orderBy,
        ));

        return count($users) ? $users->toArray() : false;
    }

    public static function isRoles($user_id, $roles)
    {
        if (! is_array($roles)) {
            $roles = array($roles);
        }

        $rows = array_filter(self::getAll(), function ($row) use ($user_id, $roles) {
            return $row['user_id'] == $user_id && in_array($row['role_id'], $roles);
        });

        return count($rows) > 0;
    }

}
